#include "px_texture2d.h"
#include "px_image.h"
#include "../utility/px_macros.h"
static GLuint _load_texture(PXIMAGE * image )
{
	GLuint textureId;
	glGenTextures(1, &textureId); //Make room for our texture
	glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit
	//Map the image to the texture
	glTexImage2D(GL_TEXTURE_2D,                //Always GL_TEXTURE_2D
		0,                            //0 for now
		GL_RGB,                       //Format OpenGL uses for image
		image->width, image->height,  //Width and height
		0,                            //The border of the image
		GL_RGB, //GL_RGB, because pixels are stored in RGB format
		GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
		//as unsigned numbers
		image->data);               //The actual pixel data
	return textureId; //Returns the id of the texture
}

static GLuint _load_texture_png(PXIMAGE * image )
{
	GLuint textureId;
	glGenTextures(1, &textureId); //Make room for our texture
	glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit
	//Map the image to the texture
	glTexImage2D(GL_TEXTURE_2D,                //Always GL_TEXTURE_2D
		0,                            //0 for now
		GL_RGBA,                       //Format OpenGL uses for image
		image->width, image->height,  //Width and height
		0,                            //The border of the image
		GL_RGBA, //GL_RGB, because pixels are stored in RGB format
		GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
		//as unsigned numbers
		image->data);               //The actual pixel data
	return textureId; //Returns the id of the texture
}


PXTEXTURE2D * create_texture2d(const char * fileName)
{
	PXTEXTURE2D *  ret = NULL;
	PXIMAGE * img =load_BMP(fileName);
	ret =(PXTEXTURE2D *)malloc(sizeof(PXTEXTURE2D));
	ret->m_textureId =_load_texture(img);
	ret->width =img->width;
	ret->height = img->height;
	PX_SAFE_FREE(img->data);
	PX_SAFE_FREE(img);
	return ret;
}

PXTEXTURE2D * create_texture2d_png( const char * fileName )
{
	PXTEXTURE2D *  ret = NULL;
	PXIMAGE * img =load_PNG(fileName);
	ret =(PXTEXTURE2D *)malloc(sizeof(PXTEXTURE2D));
	ret->m_textureId =_load_texture_png(img);
	ret->width =img->width;
	ret->height = img->height;
	PX_SAFE_FREE(img->data);
	PX_SAFE_FREE(img);
	return ret;
}
